//
//  HXSendNotifyHeadView.m
//  KD
//
//  Created by Hubery on 16/2/2.
//  Copyright © 2016年 ifly. All rights reserved.
//

#define BeginPickerTag 101
#define EndPickerTag 102

#import "HXSendNotifyHeadView.h"
#import "AWPlaceholderTextView.h"
#import "HXUpDataImageModel.h"

@interface HXSendNotifyHeadView()
@property (weak, nonatomic) IBOutlet UIButton *addimageTwoBtn;
@property (weak, nonatomic) IBOutlet UIButton *addimageOneBtn;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIView *imageContentView;
@property (weak, nonatomic) IBOutlet UITextField *titleTextField;
@property (weak, nonatomic) IBOutlet UILabel *selectedPersonLabel;

@property (weak, nonatomic) IBOutlet UITextField *timeTextField;
@property (weak, nonatomic) IBOutlet UITextField *timeActionTextField;

@property (weak, nonatomic) IBOutlet UITextField *placeTextField;

@property (weak, nonatomic) IBOutlet UIButton *userLocationBtn;
@property (weak, nonatomic) IBOutlet UITextField *userLocationTextFiield;


@property(nonatomic,weak) AWPlaceholderTextView *placeholderTextView;
@property(nonatomic,strong) UIDatePicker *endDatePicker;//EndPickerTag
@property(nonatomic,strong) UIDatePicker *beginDatePicker;//BeginPickerTag
@property(nonatomic,strong) NSMutableArray<NSMutableDictionary *> *pictArray;
@property(nonatomic,strong) UIToolbar  *keyboardDoneButtonBar;
@property(nonatomic,copy)NSString *meetingLocation;
@end

@implementation HXSendNotifyHeadView

- (void)awakeFromNib{
    AWPlaceholderTextView *textView = [[AWPlaceholderTextView alloc]init];
    self.placeholderTextView = textView;
    textView.placehoder = @"请输入内容....";
    textView.placehoderColor = [UIColor lightGrayColor];
    [self.contentView addSubview:textView];
    [self.addimageOneBtn setBackgroundImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
    [self.addimageTwoBtn setBackgroundImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
    [self setupDateTextFelid];
    self.timeActionTextField.inputAccessoryView = self.keyboardDoneButtonBar;
    self.timeTextField.inputAccessoryView = self.keyboardDoneButtonBar;
    self.userLocationTextFiield.inputAccessoryView = self.keyboardDoneButtonBar;
    self.placeholderTextView.inputAccessoryView = self.keyboardDoneButtonBar;
    self.titleTextField.inputAccessoryView = self.keyboardDoneButtonBar;
    
    UILongPressGestureRecognizer *onelongPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(oneBtnlongPressClick:)];
    onelongPress.minimumPressDuration = 1;//长按时间
    onelongPress.allowableMovement = 22;//手指抖动范围
    [self.addimageOneBtn addGestureRecognizer:onelongPress];
    
    UILongPressGestureRecognizer *twolongPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(twoBtnlongPressClick:)];
    twolongPress.minimumPressDuration = 1;//长按时间
    twolongPress.allowableMovement = 22;//手指抖动范围
    [self.addimageTwoBtn addGestureRecognizer:twolongPress];
}

-(void)oneBtnlongPressClick:(UILongPressGestureRecognizer*)press
{
    if (press.state == UIGestureRecognizerStateEnded)return;
    NSMutableDictionary *dict = self.pictArray[0];
    if (![GlobalUtil isNilValue:[dict objectForKey:@"Files_Path"]]) {//字段不是空
        [dict setObject:@"" forKey:@"Files_Path"];
        [SVProgressHUD showSuccessWithStatus:@"已删除"];
    }
    [self.addimageOneBtn setBackgroundImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
}

-(void)twoBtnlongPressClick:(UILongPressGestureRecognizer*)press
{
    if (press.state == UIGestureRecognizerStateEnded)return;
    NSMutableDictionary *dict = self.pictArray[1];
    if (![GlobalUtil isNilValue:[dict objectForKey:@"Files_Path"]]) {//字段不是空
        [dict setObject:@"" forKey:@"Files_Path"];
        [SVProgressHUD showSuccessWithStatus:@"已删除"];
    }
    [self.addimageTwoBtn setBackgroundImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
}
-(void)setupDateTextFelid{
    UIDatePicker *beginPick = [[UIDatePicker alloc]init];
    beginPick.minimumDate = [NSDate date];
    beginPick.tag = BeginPickerTag;
    self.beginDatePicker = beginPick;
    //设置只显示日期
    beginPick.datePickerMode = UIDatePickerModeDateAndTime;
    //设置文字
    beginPick.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
    self.timeActionTextField.inputView = beginPick;
    [beginPick addTarget:self action:@selector(endTimeAction:) forControlEvents:UIControlEventValueChanged];
    
    UIDatePicker *endPick = [[UIDatePicker alloc]init];
    endPick.minimumDate = [NSDate date];
    endPick.tag = EndPickerTag;
    self.endDatePicker = endPick;
    //设置只显示日期
    endPick.datePickerMode = UIDatePickerModeDateAndTime;
    //设置文字
    endPick.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
    self.timeTextField.inputView =  endPick;
    [endPick addTarget:self action:@selector(endTimeAction:) forControlEvents:UIControlEventValueChanged];
}

-(void)endTimeAction:(UIDatePicker *)picker{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone* sourceTimeZone = [NSTimeZone systemTimeZone];
    dateFormatter.timeZone = sourceTimeZone;
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    if (picker.tag == BeginPickerTag) {
        NSString *str = [dateFormatter stringFromDate: self.beginDatePicker.date];
        self.timeActionTextField.text = str;
    }else if (picker.tag == EndPickerTag){
        NSString *str = [dateFormatter stringFromDate: self.endDatePicker.date];
        self.timeTextField.text = str;
    }else{
        //NSAssert(0, @"发信息的时候时间分配错误");
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.placeholderTextView.frame = CGRectMake(10, 0, self.contentView.width, self.contentView.height);
}

-(void)setImage:(UIImage *)image tag:(NSInteger)tag{
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    if  (imageData.length>300000){
        UIImage *image = [UIImage imageWithData:imageData];
        imageData = UIImageJPEGRepresentation(image, 0.005);
    }
    //1。创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray:@[@"application/json", @"text/json",@"text/html", @"text/javascript", @"text/plain"]];
    [manager POST:[NSString stringWithFormat:@"%@/message/SendFiles.ashx",API_HOST] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"img" fileName:@"name" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        HXUpDataImageModel *dict = [[HXUpDataImageModel alloc]initWithDictionary:responseObject error:nil];
        if ([dict.code isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:@"图上传成功"];
            if (tag == 1) {
                NSMutableDictionary *mdict = self.pictArray[0];
                [mdict setObject:dict.FilePath forKey:@"Files_Path"];
                [self.addimageOneBtn setBackgroundImage:image forState:UIControlStateNormal];
            }else if (tag == 2){
                NSMutableDictionary *mdict = self.pictArray[1];
                [mdict setObject:dict.FilePath forKey:@"Files_Path"];
                [self.addimageTwoBtn setBackgroundImage:image forState:UIControlStateNormal];
            }else{
                //NSAssert(0, @"设置图片出错");
            }
        }else{
            [SVProgressHUD showErrorWithStatus:@"图上传失败"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"图上传失败"];
    }];
}

-(NSMutableDictionary *)getMessage:(NSString **)str{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
   
    if ([GlobalUtil isNilValue:self.titleTextField.text]) {//标题
        *str = @"完善信息";
        return nil;
    }
     [dict setObject:self.titleTextField.text forKey:@"Mess_Title"];
    
    
    if ([GlobalUtil isNilValue:self.timeTextField.text]) {//问题结束时间
        *str = @"完善信息";
        return nil;
    }
    [dict setObject:self.timeTextField.text forKey:@"Mess_EndDate"];

    if ([GlobalUtil isNilValue:self.timeActionTextField.text]) {//开始时间
        *str = @"完善信息";
        return nil;
    }
    [dict setObject:self.timeActionTextField.text forKey:@"Mess_OpenDate"];
    
    if ([GlobalUtil isNilValue:self.placeholderTextView.text]) {//内容
        *str = @"完善信息";
        return nil;
    }
    [dict setObject:self.placeholderTextView.text forKey:@"Mess_Content"];
    
    if ([GlobalUtil isNilValue:self.userLocationTextFiield.text]) {//地点
        *str = @"完善信息";
        return nil;
    }
    [dict setObject:self.userLocationTextFiield.text forKey:@"Mess_Add"];
    
//    if ([GlobalUtil isNilValue:self.userLocationBtn.titleLabel.text]) {//坐标
//        *str = @"开会地点";
//        return nil;
//    }
//    NSArray *locationArray = [self.userLocationBtn.titleLabel.text componentsSeparatedByString:@","];
    NSString *Mess_X = [self.userLocationDict objectForKey:@"X"];
    NSString *Mess_Y = [self.userLocationDict objectForKey:@"Y"];
    if (![GlobalUtil isNilValue:Mess_X]) {
        [dict setObject:Mess_X forKey:@"Mess_X"];//纬度
    }else{
        [dict setObject:@"" forKey:@"Mess_X"];//纬度
    }
    
    if (![GlobalUtil isNilValue:Mess_X]) {
        [dict setObject:Mess_Y forKey:@"Mess_Y"];//经度
    }else{
        [dict setObject:@"" forKey:@"Mess_Y"];//经度
    }
    
    
    NSMutableArray *mArray = [[NSMutableArray alloc]init];
    for (NSMutableDictionary *mdict in self.pictArray) {
        if (![GlobalUtil isNilValue:[mdict objectForKey:@"Files_Path"]]) {
            [mArray addObject:mdict];
        }
    }
    [dict setObject:mArray forKey:@"picList"];
    [dict setObject:@"true" forKey:@"Mess_IsSend"];
     return dict;
}

- (NSMutableArray *)pictArray{
    if (_pictArray == nil) {
        _pictArray  = [[NSMutableArray alloc]init];
        for (int i = 0; i<2; i++) {
            NSMutableDictionary *pictDict = [[NSMutableDictionary alloc]init];
            [pictDict setObject:@"imageName" forKey:@"Files_Name"];
            [pictDict setObject:@"" forKey:@"Files_Path"];
            [_pictArray addObject:pictDict];
        }

    }
    return _pictArray;
}

-(void)setUserLocationDict:(NSMutableDictionary *)userLocationDict{
    _userLocationDict = userLocationDict;
//    self.meetingLocation = [NSString stringWithFormat:@"%f,%f",userLocation.longitude,userLocation.latitude];
//    [self.userLocationBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [self.userLocationBtn setTitle:@"地点已选择,点击更换" forState:UIControlStateNormal];
    self.userLocationTextFiield.text = [userLocationDict objectForKey:@"address"];
}

- (void)setNameArray:(NSArray<NSString *> *)nameArray{
    _nameArray = nameArray;
    if (nameArray.count == 0) return;
    NSString *name = [NSString string];
    for (NSString *str in nameArray) {
        name = [name stringByAppendingString:[str stringByAppendingString:@","]];
    }
    name = [name substringToIndex:(name.length - 1)];
    self.selectedPersonLabel.text = name;
    CGSize size = [self SizeWithString:self.selectedPersonLabel.text font:[UIFont systemFontOfSize:14]];
    [self.selectedPersonLabel setFrame:CGRectMake(0, 4, size.width, 21)];
    self.selectedPersonLabel.textColor = [UIColor blackColor];
}

-(CGSize)SizeWithString:(NSString*)str font:(UIFont *)font{
    NSDictionary *dict = @{NSFontAttributeName:font};
    CGSize maxSize = CGSizeMake(MAXFLOAT, 21);
    CGSize size = [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return size;
}


-(UIToolbar*)keyboardDoneButtonBar{
    if(!_keyboardDoneButtonBar){
        _keyboardDoneButtonBar= [[UIToolbar alloc] init];
        _keyboardDoneButtonBar.barStyle = UIBarStyleDefault;
        _keyboardDoneButtonBar.tintColor = nil;
        [_keyboardDoneButtonBar sizeToFit];
        UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                                  target:nil
                                                                                  action:nil];
        UIButton *okBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [okBtn addTarget:self action:@selector(DoneClicked:) forControlEvents:UIControlEventTouchUpInside];
        okBtn.size = CGSizeMake(44, 44);
        [okBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [okBtn setTitle:@"确定" forState:UIControlStateNormal];
        okBtn.titleLabel.textColor = [UIColor blueColor];
        UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithCustomView:okBtn];
        [_keyboardDoneButtonBar setItems:[NSArray arrayWithObjects:flexItem,doneButton, nil]];
        
    }
    return _keyboardDoneButtonBar;
}
-(void)DoneClicked:(UIButton *)btn{
    
    [self endEditing:YES];
}

@end
